package com.openstack.javasdk;

import com.alibaba.fastjson.JSONObject;
import org.openstack4j.api.Builders;
import org.openstack4j.api.OSClient.OSClientV3;
import org.openstack4j.model.common.Identifier;
import org.openstack4j.model.identity.v3.Region;
import org.openstack4j.openstack.OSFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping(value = "/region")
public class RegionModule {

    //    You are not authorized to perform the requested action: identity:create_region.
    @GetMapping("/createRegion")
    public String createRegion() {
        OSClientV3 os = Auth.getOS();
        Region region = os.identity().regions()
                .create(Builders.region()
                        .id("EastRegion")
                        .description("Region for east coast")
                        .build());
        return JSONObject.toJSONString(region);
    }

    @GetMapping("/all")
    public String allRegion() {
        OSClientV3 os = Auth.getOS();
        List<? extends Region> regionList = os.identity().regions().list();
        String json = JSONObject.toJSONString(regionList);
        return json;
    }

    @GetMapping("/query")
    public String queryRegion(@RequestParam(value = "id") String id) {
        OSClientV3 os = Auth.getOS();
        Region region = os.identity().regions().get(id);
        String json = JSONObject.toJSONString(region);
        return json;
    }

//    You are not authorized to perform the requested action: identity:update_region.
    @GetMapping("/update")
    public String queryRegion() {
        OSClientV3 os = Auth.getOS();
        Region region = os.identity().regions().get("RegionOne");
        if (region != null)
            region = os.identity().regions().update(region.toBuilder().description("this is first region.").build());
        String json = JSONObject.toJSONString(region);
        return json;
    }
}
